<template>
	<a-modal
		v-model:open="visible"
		:title="title"
		:width="500"
		@ok="handleOk"
		@cancel="handleCancel"
		:confirm-loading="confirmLoading"
	>
		<a-form ref="formRef" layout="vertical" :model="formModel">
			<a-form-item name="remark">
				<a-textarea
					v-model:value="remark"
					:placeholder="'请输入' + title + '备注'"
					:auto-size="{ minRows: 3, maxRows: 6 }"
				/>
			</a-form-item>
			<a-form-item
				label="目标部门"
				name="selectedDeptId"
				v-if="isAllocation"
				:rules="[{ required: isAllocation, message: '请选择目标部门', trigger: ['change', 'blur'] }]"
			>
				<DeptSelectTree v-model="selectedDeptId" ref="deptSelectRef" />
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup>
	import assetsIssueApi from '@/api/hrms/assets/issue/assetsIssueApi'
	import DeptSelectTree from '@/components/Selector/deptSelectTree.vue'

	// 定义事件
	const emit = defineEmits(['confirm'])
	// 表单引用
	const formRef = ref()
	const deptSelectRef = ref()
	// 模态框可见性
	const visible = ref(false)
	// 确认按钮加载状态
	const confirmLoading = ref(false)
	const assetId = ref()
	const operationStatus = ref()
	const title = ref()
	// 选中的目标部门ID
	const selectedDeptId = ref()

	// 表单数据
	const remark = ref('')

	// 表单模型
	const formModel = computed(() => {
		return {
			remark: remark.value,
			selectedDeptId: selectedDeptId.value
		}
	})

	// 是否为调拨操作（只判断状态8）
	const isAllocation = computed(() => {
		return operationStatus.value === 8 // 只判断调拨中状态
	})

	// 重置表单数据
	const resetForm = () => {
		remark.value = ''
		selectedDeptId.value = null
		assetId.value = null
		operationStatus.value = null
		title.value = ''
	}

	const show = (id, status, titleText) => {
		visible.value = true
		assetId.value = id
		operationStatus.value = status
		title.value = titleText
	}

	// 确认操作
	const handleOk = async () => {
		try {
			if (formRef.value) {
				await formRef.value.validate()
			}
			confirmLoading.value = true
			await assetsIssueApi.operation(
				assetId.value,
				operationStatus.value,
				remark.value + `_deptId_${selectedDeptId.value}`
			)
			confirmLoading.value = false
			visible.value = false
			emit('confirm')
			resetForm()
		} catch (error) {
			console.error('提交失败:', error)
			confirmLoading.value = false
		}
	}

	// 取消操作
	const handleCancel = () => {
		emit('cancel')
		visible.value = false
		resetForm()
	}

	// 暴露方法给父组件
	defineExpose({
		show
	})
</script>
